package com.example.camera;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

/** Basic shell activity that hosts CameraFragment. */
public class CameraActivity extends Activity implements SensorEventListener {
    private Preview mPreview;
    Camera mCamera;
    public static int numberOfCameras = -1;
    public static int mCurrentCamera = -1; // Camera ID currently chosen
    public static int cameraCurrentlyLocked = -1; // Camera ID that's actually
						  // acquired
    public static int mDefaultCameraId = -1;
    private Button start_button;
    private Button turn_on_button;
    private TextView timer;
    private boolean isrecord = false;
    private Button change_camer_button;
    private Button back_Button;
    private boolean turn_on = false;
    private int second = 30;

    private SensorManager sm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.take_video_layout);
	getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
	mPreview = (Preview) findViewById(R.id.preview);
	timer = (TextView) findViewById(R.id.arc_hf_video_timer);
	change_camer_button = (Button) findViewById(R.id.change_camer_button);
	start_button = (Button) findViewById(R.id.take_video_start_button);
	start_button.setOnClickListener(new Button_listener());
	back_Button = (Button) findViewById(R.id.back_button);
	back_Button.setOnClickListener(new Button_listener());
	turn_on_button = (Button) findViewById(R.id.turn_on_light);
	turn_on_button.setOnClickListener(new Button_listener());

	if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
	    numberOfCameras = Camera.getNumberOfCameras();
	    // Find the ID of the rear-facing ("default") camera
	    CameraInfo cameraInfo = new CameraInfo();
	    for (int i = 0; i < numberOfCameras; i++) {
		Camera.getCameraInfo(i, cameraInfo);
		if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) {
		    mCurrentCamera = mDefaultCameraId = i;
		    LogUtil.d("CameraActivity", "检查了有几个摄像头" + numberOfCameras);
		}
	    }
	}

	change_camer_button.setOnClickListener(new OnClickListener() {

	    @Override
	    public void onClick(View v) {
		mPreview.switchCamera();
	    }
	});
    }

    class Button_listener implements OnClickListener {

	@Override
	public void onClick(View v) {
	    if (v.getId() == R.id.take_video_start_button) {
		if (isrecord) {
		    change_camer_button.setEnabled(true);
		    isrecord = false;
		    mPreview.mStopRecord();
		    handler.removeCallbacks(task);
		    finish();
		} else {
		    isrecord = true;
		    change_camer_button.setEnabled(false);
		    mPreview.mStartRecord();
		    start_button
			    .setBackgroundResource(R.drawable.take_video_start_select);
		    start_button.setEnabled(false);
		    handler.postDelayed(task, 1000);
		}
	    }
	    if (v.getId() == R.id.back_button) {
		mPreview.Cancle();
		finish();
	    }
	    if (v.getId() == R.id.turn_on_light) {
		if (!isrecord) {
		    if (turn_on) {
			turn_on_button
				.setBackgroundResource(R.drawable.btn_off);
			turn_on = false;
		    } else {
			turn_on_button.setBackgroundResource(R.drawable.btn_on);
			turn_on = true;
		    }
		    mPreview.setTurn_on(turn_on);
		}
	    }
	}
    }

    @Override
    public void onBackPressed() {
	if (isrecord) {
	    mPreview.Cancle();
	}
	finish();
    }

    private Handler handler = new Handler() {

	@Override
	public void handleMessage(Message msg) {
	    super.handleMessage(msg);
	    if (msg.what == 0) {
		isrecord = false;
		mPreview.mStopRecord();
		handler.removeCallbacks(task);
		finish();
	    }
	    if (msg.what == 123) {
		int orientation = msg.arg1;
		if (mPreview.cameraCurrentlyLocked == 0) {
		    if (orientation > 45 && orientation < 135) {
			// SCREEN_ORIENTATION_REVERSE_LANDSCAPE
			// System.out.println("横屏1");
			mPreview.setRorate(180);
		    } else if (orientation > 135 && orientation < 225) {
			// SCREEN_ORIENTATION_REVERSE_PORTRAIT
			// System.out.println("竖屏1");
			mPreview.setRorate(270);
		    } else if (orientation > 225 && orientation < 315) {
			// SCREEN_ORIENTATION_LANDSCAPE
			// System.out.println("横屏2");
			mPreview.setRorate(0);
		    } else if ((orientation > 315 && orientation < 360)
			    || (orientation > 0 && orientation < 45)) {
			// SCREEN_ORIENTATION_PORTRAIT
			// System.out.println("竖屏2");
			mPreview.setRorate(90);
		    }
		} else {
		    if (orientation > 45 && orientation < 135) {
			// SCREEN_ORIENTATION_REVERSE_LANDSCAPE
			System.out.println("横屏1");
			mPreview.setRorate(180);
		    } else if (orientation > 135 && orientation < 225) {
			// SCREEN_ORIENTATION_REVERSE_PORTRAIT
			System.out.println("竖屏1");
			mPreview.setRorate(90);
		    } else if (orientation > 225 && orientation < 315) {
			// SCREEN_ORIENTATION_LANDSCAPE
			System.out.println("横屏2");
			mPreview.setRorate(0);
		    } else if ((orientation > 315 && orientation < 360)
			    || (orientation > 0 && orientation < 45)) {
			// SCREEN_ORIENTATION_PORTRAIT
			System.out.println("竖屏2");
			mPreview.setRorate(270);
		    }
		}
	    }
	}

    };

    /*
     * 定时器设置，实现计时
     */
    private Runnable task = new Runnable() {
	public void run() {
	    if (isrecord) {
		handler.postDelayed(this, 1000);
		second--;
		timer.setText("00:" + TimesUtils.format(second));
		if (second == 28)//防止马上停止，引发相机崩溃
		    start_button.setEnabled(true);
		if (second == 0) {
		    handler.sendEmptyMessage(0);
		}
	    }
	}
    };

    @Override
    public void onResume() {
	super.onResume();
	sm = (SensorManager) getSystemService(SENSOR_SERVICE);
	sm.registerListener(this,
		sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
		SensorManager.SENSOR_DELAY_NORMAL);
	try {
	    if (numberOfCameras != -1) {
		mCamera = Camera.open(mCurrentCamera);
		cameraCurrentlyLocked = mCurrentCamera;
	    } else {
		mCamera = Camera.open();
	    }
	    mPreview.setCamera(mCamera);
	} catch (Exception e) {
	    dialog("相机异常");
	}
    }

    protected void dialog(String message) {
	AlertDialog.Builder builder = new Builder(CameraActivity.this);
	builder.setMessage(message);
	builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {

	    @Override
	    public void onClick(DialogInterface dialog, int which) {
		dialog.dismiss();
		finish();
	    }
	});
	builder.create().show();
    }

    @Override
    public void onPause() {
	super.onPause();
	sm.unregisterListener(this);
	if (mCamera != null) {
	    mPreview.setCamera(null);
	    mCamera.release();
	    mCamera = null;
	    handler.removeCallbacks(task);
	}
    }

    private static final int _DATA_X = 0;
    private static final int _DATA_Y = 1;
    private static final int _DATA_Z = 2;
    public static final int ORIENTATION_UNKNOWN = -1;

    @Override
    public void onSensorChanged(SensorEvent event) {
	float[] values = event.values;
	int orientation = ORIENTATION_UNKNOWN;
	float X = -values[_DATA_X];
	float Y = -values[_DATA_Y];
	float Z = -values[_DATA_Z];
	float magnitude = X * X + Y * Y;
	// Don't trust the angle if the magnitude is small compared to the y
	// value
	if (magnitude * 4 >= Z * Z) {
	    float OneEightyOverPi = 57.29577957855f;
	    float angle = (float) Math.atan2(-Y, X) * OneEightyOverPi;
	    orientation = 90 - (int) Math.round(angle);
	    // normalize to 0 - 359 range
	    while (orientation >= 360) {
		orientation -= 360;
	    }
	    while (orientation < 0) {
		orientation += 360;
	    }
	}

	if (handler != null) {
	    handler.obtainMessage(123, orientation, 0).sendToTarget();
	}

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }
}
